package com.mhkj.revise.professional.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.mhkj.base.busiType.entity.BusinessType;
import com.mhkj.base.busiType.service.BusinessTypeService;
import com.mhkj.base.templete.entity.PlanTemplete;
import com.mhkj.base.templete.entity.PlanTempleteData;
import com.mhkj.base.templete.service.PlanTempleteService;
import com.mhkj.common.enums.PlanType;
import com.mhkj.common.util.ItemHelper;
import com.mhkj.revise.mainPlan.service.MainPlanService;
import com.mhkj.revise.plan.entity.Plan;
import com.mhkj.revise.plan.entity.PlanNode;
import com.mhkj.revise.professional.repository.ProfessionalPlanRepository;
import com.mhkj.revise.professional.service.ProfessionalPlanNodeService;
import com.mhkj.revise.professional.service.ProfessionalPlanService;
import com.mics.core.common.componet.Pagination;
import com.mics.core.common.exception.ErrorCode;
import com.mics.core.common.exception.ParamException;
import com.mics.core.system.base.service.impl.BaseServiceImpl;
import com.mics.core.system.organizational.service.OrgService;
import com.mics.core.system.rbac.entity.Dictionary;
import com.mics.core.system.rbac.service.DictionaryService;

/**
 * 专项计划
 * @author mics
 * @date 2018年8月20日
 * @version 1.0
 */
@Service
public class ProfessionalPlanServiceImpl extends BaseServiceImpl<Plan> implements ProfessionalPlanService{
	@Resource
	private ProfessionalPlanRepository professionalPlanRepository;
	@Resource
	private DictionaryService dictionaryService;
	@Resource
	private MainPlanService mainPlanService;
	@Resource
	private PlanTempleteService planTempleteService;
	@Resource
	private OrgService orgService;
	@Resource
	private ProfessionalPlanNodeService professionalPlanNodeService;
	@Resource
	private BusinessTypeService businessTypeService;
	@Resource
	private ItemHelper itemHelper;
	
	@Resource
	public void setProfessionalPlanRepository(
			ProfessionalPlanRepository professionalPlanRepository) {
		super.setBaseRepository(professionalPlanRepository);
	}

	@Override
	public Pagination<Plan> listByPage(Plan plan, int pageIndex, int pageSize) {
		Specification<Plan> spec = new Specification<Plan> () {  
			/**
			 * 序列号
			 */
			private static final long serialVersionUID = -786003485941679959L;
			@Override
			public Predicate toPredicate(Root<Plan> root, CriteriaQuery<?> query,
					CriteriaBuilder criteriaBuilder) {
              List<Predicate> lstPredicates = new ArrayList<Predicate>();
              if(itemHelper.getCurrentUserItems().size() > 0 ){
					Predicate p3=criteriaBuilder.and(root.get("item").in(itemHelper.getCurrentUserItems()));
		            lstPredicates.add(p3);
				}else{
					Predicate p3=criteriaBuilder.and(root.get("item").in(0));
		            lstPredicates.add(p3);
				}
              if(!StringUtils.isEmpty(plan.getName())){
                  Predicate p1=criteriaBuilder.like(root.get("name").as(String.class), "%"+plan.getName()+"%");
                  lstPredicates.add(p1);
              }
        	  Dictionary planTyped = dictionaryService.getByCode(PlanType.PROFESSION_TYPE.getCode());
              Join<Object, Object> planType = root.join("planType",JoinType.INNER);
              Predicate p1=criteriaBuilder.equal(planType.get("id").as(Long.class), planTyped.getId());
              lstPredicates.add(p1);
              
              if(plan.getState() == 0){
                  Predicate p2=criteriaBuilder.notEqual(root.get("state").as(Integer.class),0);
                  lstPredicates.add(p2);
              }else {
                  Predicate p2=criteriaBuilder.equal(root.get("state").as(Integer.class),0);
                  lstPredicates.add(p2);
              }
              Predicate[] arrayPredicates = new Predicate[lstPredicates.size()];
              return criteriaBuilder.and(lstPredicates.toArray(arrayPredicates));
	        }
		};
		Page<Plan> pageT =  professionalPlanRepository.findAll(spec, PageRequest.of(pageIndex, pageSize, Sort.Direction.ASC,"id"));
		Pagination<Plan> pagination = new Pagination<Plan>();
		pagination.setTotal(professionalPlanRepository.count(spec));
		List<Plan> Plans = pageT.getContent();
		pagination.setData(Plans);
		return pagination;
	}


	@Override
	@Transactional(rollbackOn=Exception.class)
	public String save(Plan plan) {
		//保存计划 
		Plan parentPlan = mainPlanService.getById(plan.getPlan().getId());
		plan.setItem(parentPlan.getItem());
		super.save(plan);
		//保存计划节点
		savePlanNode(plan);
		return null;
	}
	

	//创建计划节点
	private void savePlanNode(Plan plan) {
		PlanTemplete planTemplete = planTempleteService.getById(plan.getPlanTemplete().getId());
		List<PlanTempleteData> planTempleteDatas = planTemplete.getPlanTempleteDatas();
		if(planTempleteDatas != null && planTempleteDatas.size() > 0){
			for(int i = 0 ;i< planTempleteDatas.size();i++){
				PlanTempleteData planTempleteData = planTempleteDatas.get(i);
				PlanNode planNode = new PlanNode();
				planNode.setPlan(plan);
				planNode.setNO(planTempleteData.getNO());
				//节点名称
				planNode.setNodeName(planTempleteData.getNodeName());
				//业务类型
				BusinessType businessType =businessTypeService.getById(planTempleteData.getBusinessType().getId());
				planNode.setBusiness(businessType);
				//节点性质
				planNode.setNodeProperty(planTempleteData.getNodeProperty());
				//完成标准
				planNode.setCompleteStandard(planTempleteData.getCompleteStandard());
				//工期
				planNode.setDeadline(planTempleteData.getDeadline());
				//工期说明
				planNode.setDeadlineDesc(planTempleteData.getDeadlineDesc());
				//责任单位
				planNode.setCompanyId(planTempleteData.getCompanyId());
				//责任部门
				planNode.setOfficeId(planTempleteData.getOfficeId());
				//岗位
				planNode.setPostId(planTempleteData.getPostId());
				//监督
				planNode.setSupervise(planTempleteData.getSupervise());
				//备注
				planNode.setRemark(planTempleteData.getRemark());
				planNode.setNodeTempleteDataId(planTempleteData);
				professionalPlanNodeService.save(planNode);
			}
		}else{
			throw new ParamException(ErrorCode.PARAM_ERROR, "模板数据不能为空！");
		}
		
	}
}
